package com.kepler.social.web.comp;


import com.kepler.social.common.constants.BusinessState;
import com.kepler.social.common.exception.ServiceException;
import com.kepler.social.common.exception.SystemException;
import com.kepler.social.web.common.HttpResult;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理 Exception 异常
     * 这个是兜底用的
     *
     * @param httpServletRequest httpServletRequest
     * @param e                  异常
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public HttpResult exceptionHandler(HttpServletRequest httpServletRequest, Exception e) {
        logger.error("系统错误:", e);
        return new HttpResult(BusinessState.UNKNOWN_ERROR.code, e.getMessage());
    }

    /**
     * 处理 BusinessException 异常
     *
     * @param httpServletRequest httpServletRequest
     * @param e                  异常
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = IllegalArgumentException.class)
    public HttpResult IllegalArgumentExceptionHandler(HttpServletRequest httpServletRequest, IllegalArgumentException e) {
        logger.info("参数异常 msg:" + e.getMessage());
        return new HttpResult(BusinessState.PARAM_ERROR.code, e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(value = ServiceException.class)
    public HttpResult ServiceExceptionHandler(HttpServletRequest httpServletRequest, ServiceException e) {
        logger.info("服务异常:" + e.getMessage());
        return new HttpResult(BusinessState.BUSINESS_ERROR.code, e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(value = SystemException.class)
    public HttpResult SystemExceptionHandler(HttpServletRequest httpServletRequest, SystemException e) {
        logger.info("系统异常:" + e.getMessage());
        return new HttpResult(BusinessState.SYS_ERROR.code, e.getMessage());
    }

}
